#include "vtor_flash_eeprom.h"

#ifdef __VTOR_FLASH_EEPROM__

// 加入用户工程宏
#ifdef __VTOR_FLASH_EEPROM__

#include "main.h"
#include "vtor_printf.h"



VtorFlashEeprom demoEeprom = 
{
	.flashStartAddress = 0x08006000,
	.flashPageSize = 0x0400,
	.flashPageCnt = 4,
	.eepromSize = 0x0100,
};


// 一般只擦除1个可擦除单位
uint32_t VtorFlash_Erase(uint32_t addr)
{
	uint32_t error = 0;
	FLASH_EraseInitTypeDef eraseStruct;
	eraseStruct.TypeErase = FLASH_TYPEERASE_PAGES;
	eraseStruct.Banks = 0;
	eraseStruct.PageAddress = addr;
	eraseStruct.NbPages = 1;
	HAL_FLASH_Unlock();
	HAL_FLASHEx_Erase(&eraseStruct, &error);
	HAL_FLASH_Lock();
	return error;
}

// 如果是全0xff，返回0，代表可以直接执行写操作
// 如果不是全0xff，返回1，代表flash上有有效数据
uint8_t VtorFlash_CheckValid(uint32_t addr, uint32_t len)
{
	for(int i = 0; i < len; i += 4)
	{
		// 如果不是全f，说明写过数据，说明数据有效
		if(0xffffffff != *(uint32_t*)(addr + i))
		{
			return 1;
		}
	}
	return 0;
}



uint32_t VtorFlash_Write(uint32_t addr, uint32_t* data, uint32_t len)
{
	if(0 == addr || 0 == len)
	{
		return 0;
	}
	if(addr & 0x03 || len & 0x03)
	{
		return 0;
	}
	HAL_FLASH_Unlock();
	for(uint32_t i = 0; i< len; i += 4)
	{
		HAL_StatusTypeDef flashRet =
			HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, addr + i, data[i / 4]);
		// 如果出错，直接返回
		if(HAL_OK != flashRet)
		{
			HAL_FLASH_Lock();
			return 0;
		}
	}
	HAL_FLASH_Lock();
	return addr;
}


uint32_t VtorFlash_Read(uint32_t addr, uint32_t* data, uint32_t len)
{
	if(0 == addr || 0 == len)
	{
		return 0;
	}
	if(addr & 0x03 || len & 0x03)
	{
		return 0;
	}
	for(uint32_t i = 0; i < len; i+=4)
	{
		data[i] = *(uint32_t*)(addr + i / 4);
	}
	return addr;
}





#endif // __USER_PROJECT__

#endif // __VTOR_FLASH_EEPROM__

